import React from "react"
import ReactDOM from "react-dom"
import { Template } from "./Redirect.template.js"
import AJAX from "../../lib/ajax_pay"
import Tools from "../../lib/tools"
import Loading from "../../components/Loading/Loading"
import wx from 'wx'
import { addErrorListener } from '../../lib/handleError'

import "../../lib/resetFont"
import "./Redirect.less"

class App extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            code: Tools.getParams().code,
            appid: Tools.getParams().appid,
            source: Tools.getParams().source,
            loading: true,
            loading_text: "加载中...",
            type: null                      // Charge: 支付，Recharge: 充值
        }
    }

    componentWillMount() {
        addErrorListener()()
        AJAX.appendBaiduAnalysis()
        const { code, appid } = this.state
        if (code) {
            AJAX.request("check", { code, appid }, data => {
                if (data.code === 0) {
                    this.setState({
                        loading: false,
                        is_subed: data.body.is_subed,
                        qrcode_img: data.body.qrcode_img,
                        name: data.body.name
                    })
                }
            })
        } else {
            AJAX.auth()
        }
    }

    render() {
        const { loading, loading_text, is_subed, name, qrcode_img, source } = this.state
        let content = <div>
            <Loading show={loading} text={loading_text} />
        </div>
        const data = {
            name,
            qrcode_img,
            source
        }
        if (loading === false) {
            if (is_subed === 1) {
                // window.location.href = "./PickUp";
                const wx_type = window.localStorage.getItem('wx_type');
                window.location.href = `./PickUp?wx_type=${wx_type}`;
            } else {
                window.location.href = qrcode_img;
                // content = <Template {...data} />
            }
        }
        return content
    }
}
ReactDOM.render(<App />, document.getElementById('app'))